#include "meswizard.h"
#include "ui_meswizard.h"

int MesWizard::currentDialog = 0;

MesWizard::MesWizard(QWidget *parent) : QDialog(parent), ui(new Ui::MesWizard)
{
    inserted = false;
    ui->setupUi(this);
    ui->textEdit->setTabStopWidth(40);
    ui->textEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
    setFixedSize(500, 300);
    ui->textEdit->setFocus();
}

MesWizard::~MesWizard()
{
    delete ui;
}

void MesWizard::on_btnCancel_clicked()
{
    close();
}

void MesWizard::closeEvent(QCloseEvent *e)
{
    if(!ui->textEdit->document()->isEmpty() && !inserted)
    {
        QMessageBox::StandardButton choice = QMessageBox::warning(this, tr("Fermer l'assistant"), tr("Une saisie a été effectuée. Êtes-vous sûr de vouloir fermer ?"), QMessageBox::Yes | QMessageBox::No);
        (choice == QMessageBox::Yes) ? e->accept() : e->ignore();
    }
}

void MesWizard::on_btnColor_clicked()
{
    eNPC::fillColor(ui->textEdit);
}

void MesWizard::on_btnNextcmd_clicked()
{
    ui->textEdit->appendPlainText("<NEXT>\n");
    ui->textEdit->setFocus();
}

void MesWizard::on_btnInsert_clicked()
{
    inserted = true;
    emit mesInserted(ui->textEdit->document()->toPlainText());
}

void MesWizard::on_btnInfo_clicked()
{
    QMessageBox::information(this, tr("Aide"), tr("Cet assistant permet de saisir rapidement les messages envoyés par vos scripts :\n- N'insérez que le texte que vous souhaitez voir apparaître en jeu.\n- Chaque saut de ligne équivaut à une nouvelle commande mes.\n- Cliquez sur l'icône (ou utilisez CTRL+N) correspondant pour insérer une commande next."), QMessageBox::Ok);
}

void MesWizard::on_btnPreview_clicked()
{
    QDialog preview;
    QPushButton close(tr("Fermer"), &preview), next(tr("Suivant"), &preview);
    messageBox = new QTextEdit(&preview);

    preview.setWindowFlags(Qt::FramelessWindowHint);
    preview.setStyleSheet("QDialog { background: white url(:/ro/ro/dialogbox.png) no-repeat right bottom; }");
    preview.setFixedSize(278, 178);

    close.setGeometry(231, 154, 42, 20);
    close.setStyleSheet("border-image: url(:/ro/ro/btn.png); font-size: 10px;");
    close.setCursor(Qt::PointingHandCursor);
    connect(&close, SIGNAL(clicked()), &preview, SLOT(close()));

    next.setGeometry(231, 154, 42, 20);
    next.setStyleSheet("border-image: url(:/ro/ro/btn.png); font-size: 10px;");
    next.setCursor(Qt::PointingHandCursor);
    connect(&next, SIGNAL(clicked()), this, SLOT(nextDialog()));
    next.setVisible(false);

    messageBox->setGeometry(10, 10, 260, 140);
    messageBox->setStyleSheet("border: 0; background-color: #F5F5F5");
    messageBox->setReadOnly(true);
    messageBox->viewport()->setCursor(Qt::ArrowCursor);
    messageBox->viewport()->setFixedWidth(fontMetrics().width(QLatin1Char('9')) * 35); /* 35 caractères max par ligne */
    messageBox->setFont(QFont("Arial", 9)); /* ~ looks like in-game font */
    connect(this, SIGNAL(dialogSwitched(QString)), messageBox, SLOT(setText(QString)));
    connect(messageBox, SIGNAL(textChanged()), this, SLOT(colorizeCurrentDialog()));

    /* Le bouton "suivant" apparaît au dessus du bouton "fermer"
      Si le NPC a fini de parler, on masque "Suivant" */
    connect(this, SIGNAL(dialogEnded()), &next, SLOT(hide()));

    dialogs = ui->textEdit->toPlainText().split("<NEXT>\n", QString::SkipEmptyParts);
    if(dialogs.count() > 0) messageBox->setText(dialogs.first());

    if(dialogs.count() > 1)
    {
        next.setVisible(true);
        currentDialog++;
    }

    preview.exec();
}

void MesWizard::nextDialog()
{
    emit dialogSwitched(dialogs.at(currentDialog++));

    if(dialogs.count() == currentDialog)
    {
        emit dialogEnded(); /* Désactive "Suivant" et affiche "Fermer" */
        currentDialog = 0;
    }
}

void MesWizard::colorizeCurrentDialog()
{
    QRegExp colorizedText("\\^([abcdefABCDEF0-9]{6})([^\\^]*)");
    int p = 0;

    while((p = colorizedText.indexIn(messageBox->toPlainText(), p)) != -1)
    {
        messageBox->setPlainText(messageBox->toPlainText().replace(p, colorizedText.matchedLength(), colorizedText.cap(2)));

        QList<QTextEdit::ExtraSelection> selections = messageBox->extraSelections();
        QTextEdit::ExtraSelection selection;
        QTextCharFormat format = selection.format;
        format.setForeground(QColor("#"+colorizedText.cap(1)));
        selection.format = format;

        QTextCursor cursor = messageBox->textCursor();
        cursor.setPosition(p);
        cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, colorizedText.cap(2).length());

        selection.cursor = cursor;
        selections.append(selection);
        messageBox->setExtraSelections(selections);

        p += colorizedText.cap(2).length();
    }
}
